//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// File: Analyser_IO
//
// Handles IO lines of the analyser
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------

#include "firmware.h"
                                           
//---------------------------------------------------------------------------
// SetIoDefaults - Init IO and assing default settings
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
void SetIoDefaults()                                  
{  
   // Led pin D2 ouptut, high (led off)
   PinSet(DDRD, 2);  
   RedLed(0);
                                                      
   // databus gate pin A7 output & disable gate (set to tristate)
   PinSet (DDRA, 7);
   GateEnable(0);

   // counter reset pin D7 output, low
   PinSet   (DDRD, 7);
   PinClear(PORTD, 7);
   
   // memory read pin B3 output, high
   PinSet (DDRB, 3);
   PinSet(PORTB, 3);
   
   // memory write pin D5 output, clear
   PinSet (DDRD, 5);
   PinClear(PORTD, 5);
   
   // databus portc input             
   DDRC=0x00;
}

void GateEnable(bool in)
{
   if (in) {
      PinClear(PORTA, 7);
   } else {
      PinSet(PORTA, 7);
   }
}

void RedLed(bool in)
{
   if (in) {
      PinClear(PORTD, 2);
   } else {
      PinSet(PORTD, 2);
   }
}

void CounterResetPulse()
{
   PinSet(PORTD, 7);
   asm("nop");
   asm("nop");
   asm("nop");
   PinClear(PORTD, 7);
}

unsigned char MemoryReadPulse()
{  unsigned char Ret;
   
   PinClear(PORTB, 3);
   asm("nop");
   asm("nop");
   asm("nop");
//  Waitms(1);   
   Ret = PINC;
   PinSet(PORTB, 3);
   
   return Ret;
}

void MemorySamplePulse()
{
   PinSet(PORTD, 5);
   asm("nop");
   asm("nop");
   asm("nop");
   PinClear(PORTD, 5);
}

void MemoryWritePulse(unsigned char Value)
{
   DDRC = 0xFF;            // set PORTC to output  
   PORTC = Value;          // put data on port 
   MemorySamplePulse();    // pulse clock
   DDRC = 0x00;            // set PORTC to input      
}


// SetCounterPosition - Reset counter and increment to requested position.
void SetCounterPosition(long int Pos)
{  int i;
   
   // reset address counter
   CounterResetPulse();
                       
   // go to first memory location                       
   for (i=0; i<Pos; i++) {
      MemoryReadPulse();
   }                    
}        
